package com.fare.taluo.action.crawl;



import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fare.taluo.application.crawl.ICrawlFreightPriceApplication;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.application.plane.income.FreightPublishApplication;
import com.fare.taluo.base.struts2.json.BaseJsonStrutsAction;
import com.fare.taluo.vo.core.FreightPublishVO;
import com.fare.taluo.vo.core.PlaneInfo;
import com.opensymphony.xwork2.ActionContext;


/**
 * 实时获取运价action
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
@Namespace("/crawl/realtime")
public class RealtimeCrawlAction extends BaseJsonStrutsAction{
	private static final long serialVersionUID = 1L;
	public Logger logger = LoggerFactory.getLogger(RealtimeCrawlAction.class);
	private String depCity;//出发城市
	private String arrCity;//到达城市
	private String flightDate;//起飞日期
	private String flag;//判断是否使用IP代理
	private String endDate;//截至日期
	private String[] flightTimes; //航班时间点，(上午，中午，下午，晚上)
	private String carrierKey;//运营商key 如CA等
	private PlaneInfo planeInfo;
	private List<PlaneInfo> ps;
	private final long TIMING=10*60*1000;//定时，十分钟
	private boolean canCrawl;//是否能抓取，配合客户端
	private final String LAST_CRAWL_TTME="LAST_CRAWL_TTME";//最后一次抓取的时间
	private String hbaseKey;
	private FreightPublishVO freightPublishVO;
	@Resource(name="sourceApplication")
	private SourceApplication sourceApplication; 
	@Resource(name="freightPublishApplication")
    private FreightPublishApplication freightPublishApplication ;
	@Resource(name="portApplication")
	private PortApplication portApplication;
	@Inject
	private ICrawlFreightPriceApplication crawlFreightPriceApplication;
	private String fromCityCode;
	private String toCityCode;
	private String fromCity;
	private String toCity;
	/**
	 * “即时抓取”页面
	 * @return
	 */
	@Action(value="toJsp",results={@Result(name="dispatcher", type="dispatcher",location="/fare/realtimeCrawl.jsp")})
	public String toJsp(){
		return "dispatcher";
	}
	/**
	 * 通知服务器客户端即将抓取数据
	 * 返回true/false告知客户端是否成功发起查询，后面异步获取数据
	 * @return
	 * @throws Exception
	 */
	@Action(value="notifyCrawl", results={@Result(name="JSON", type="json", params={"root","canCrawl"})})
	public String notifyCrawl()throws Exception{
		Object lastTimeObj=ActionContext.getContext().getSession().get(this.LAST_CRAWL_TTME);
		//上次时间
		long lastTime=lastTimeObj==null||"".equals(String.valueOf(lastTimeObj).trim())?-1:Long.parseLong(String.valueOf(lastTimeObj).trim());
		Date now=new Date();
		if(lastTime==-1 || now.getTime()-lastTime>this.TIMING){
			this.canCrawl=true;
			//将现在时间放入session
//			ActionContext.getContext().getSession().put(LAST_CRAWL_TTME, new Date().getTime());
		}else{
			this.canCrawl=false;//不允许抓取
		}
		return "JSON";
	}
	/**
	 * 抓取【某个】公司【某天】【某条航线】的【最低价】航班
	 * @return
	 */
	@Action(value="crawlLowestPlaneInfoByCompany", results={@Result(name="JSON", type="json", params={"root","planeInfo"})})
	public String crawlLowestPlaneInfoByCompany()throws Exception{
		if( flag ==null || flag.length()==0 || "".equals(flag)){
			flag="0";
		}
		long stime = System.currentTimeMillis();
		planeInfo = crawlFreightPriceApplication.crawlLowestPlaneInfoByCompany(fromCity, toCity, flightDate, flightTimes,carrierKey,flag);
		logger.info("共耗时ms："+(System.currentTimeMillis()-stime));
		return "JSON";
	}
	
	/**
	 * 抓取【某个】公司【某天】【某条航线】的【所有】航班
	 * @return
	 * @throws Exception 
	 */
	@Action(value="crawlAllPlaneInfosByCompany")
	public void crawlAllPlaneInfosByCompany() throws Exception{
		long stime = System.currentTimeMillis();
		//flightDate  yyyy-MM-dd
		//carrierKey  CZ
	    carrierKey = sourceApplication.findByHbaseKey(hbaseKey).getCarrierKey();
	    
	  /*  String toCode = portApplication.findPortEntityByCityName(depCity).getPortCode();
		String arrCode = portApplication.findPortEntityByCityName(arrCity).getPortCode();*/
	    String toCode = fromCityCode;
	  		String arrCode = toCityCode;
	  	freightPublishVO = freightPublishApplication.findByLine(toCode, arrCode);

		ps=crawlFreightPriceApplication.crawlAllPlaneInfosByCompany(fromCity, toCity, flightDate, null, carrierKey);//20001
		logger.info("共耗时ms："+(System.currentTimeMillis()-stime));
		
		String json = com.fare.taluo.util.JsonUtil.toJson(ps);
		int totalRows = 0;
		if(ps!=null&&ps.size()>0){
			totalRows = ps.size();
		}
		
		String jsonStr = "{\"Total\":"+totalRows+","+ "\"Rows\":"+json+"}";
		String stardardPrice = null;
		if(freightPublishVO==null){
			logger.error("该航线没有标准运价，请再次配置!");
			stardardPrice = "null";
		}else{
			stardardPrice =  ""+freightPublishVO.getStandardPrice();
		}
		
		String data = "{\"json\":"+jsonStr+","+ "\"standardPrice\":"+freightPublishVO.getStandardPrice()+"}";//standardPrice
		super.toJSONOut(data);
	}
	
	

	public String getDepCity() {
		return depCity;
	}

	public void setDepCity(String depCity) {
		this.depCity = depCity;
	}

	public String getArrCity() {
		return arrCity;
	}

	public void setArrCity(String arrCity) {
		this.arrCity = arrCity;
	}


	public String getFlag() {
		return flag;
	}
	public void setFlag(String flag) {
		this.flag = flag;
	}
	public String getFlightDate() {
		return flightDate;
	}

	public void setFlightDate(String flightDate) {
		this.flightDate = flightDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String[] getFlightTimes() {
		return flightTimes;
	}

	public void setFlightTimes(String[] flightTimes) {
		this.flightTimes = flightTimes;
	}

	public boolean isCrawl() {
		return canCrawl;
	}

	public void setCrawl(boolean isCrawl) {
		this.canCrawl = isCrawl;
	}

	public String getCarrierKey() {
		return carrierKey;
	}

	public void setCarrierKey(String carrierKey) {
		this.carrierKey = carrierKey;
	}

	
	public boolean isCanCrawl() {
		return canCrawl;
	}

	public void setCanCrawl(boolean canCrawl) {
		this.canCrawl = canCrawl;
	}

	
	public PlaneInfo getPlaneInfo() {
		return planeInfo;
	}
	public void setPlaneInfo(PlaneInfo planeInfo) {
		this.planeInfo = planeInfo;
	}
	public List<PlaneInfo> getPs() {
		return ps;
	}
	public void setPs(List<PlaneInfo> ps) {
		this.ps = ps;
	}
	public String getHbaseKey() {
		return hbaseKey;
	}
	public void setHbaseKey(String hbaseKey) {
		this.hbaseKey = hbaseKey;
	}
	public String getFromCityCode() {
		return fromCityCode;
	}
	public void setFromCityCode(String fromCityCode) {
		this.fromCityCode = fromCityCode;
	}
	public String getToCityCode() {
		return toCityCode;
	}
	public void setToCityCode(String toCityCode) {
		this.toCityCode = toCityCode;
	}
	public String getFromCity() {
		return fromCity;
	}
	public void setFromCity(String fromCity) {
		this.fromCity = fromCity;
	}
	public String getToCity() {
		return toCity;
	}
	public void setToCity(String toCity) {
		this.toCity = toCity;
	}
	
	
}
